<!-- 新鲜事 -->
<!-- 小默子 8/21更新 -->
<!-- 小默子 2020/8/23更新 增加跳转 -->
<!-- 小默子 2020/8/24更新 增加点击新建帖子按钮 -->
<!-- 小默子 2020/9/10更新 重构页面代码 -->
<!-- 桃子 2020/9/22增加了判断更新 -->
<template>
	<view class="interest"> 
		<!-- 加载时的页面 -->
		<view class="loading" v-if="isLoading" :style="'height:' + loadingHeight + 'px;width: 100%;'">
			<text :style="'display: block; width: 100%; height: 100%; line-height: ' + loadingHeight + 'px; text-align: center; color:#999'">加载中...</text>
		</view>
		<ErrorPage v-if='err' @reloadPage='reloadPage'></ErrorPage>
		<view class="interestPage" v-if="!isLoading && !err">
		<!-- 用来将页面整体向下顶，给屏幕状态栏留出空间 -->
			<view class="status_bar"></view>	
			<!-- 顶栏 --> 
			<view class="top-nav">
				<view class="top">
					<!-- 左侧头像 --> 
					<view class="avatar">
						<!-- 已登陆时 -->
						<view @tap="myInforTo" v-if="isLogin">
							<view class="login loginStatus">
								<image :src="this.myAvatar" mode="aspectFill"></image>
								<Level class="mylevel" :level='this.mylevel'></Level>
								<!-- <view class="mylevel">
									Lv {{this.mylevel}}
								</view> -->
							</view>
						</view>
						<!-- 未登录 -->
						<navigator hover-class="none" url="../Login/Login" v-else><view class="notLogin loginStatus">登录</view></navigator>
					</view>
					
					<!-- 搜索框 -->
					<SearchBox class="searchBox" @click.native="searchTo()"></SearchBox>
					
					<view class="information" @tap='toMessage'>
						<text class="inxupt inxupttubiao1"></text>
						<view class="infoCount" v-show='messages_num != 0'>
							{{messages_num}}
						</view>
					</view>					
				</view>
				
				<!-- 滑动导航栏 -->
				<view class="swiperNav">
					<scroll-view scroll-x="true" scroll-with-animation class="scroll-tab" :scroll-left="scrollLeft">
						<view>
							<block v-for="(navBar,index) in navBars" :key="index">
								<view class="scroll-tab-item"  @tap="swichTab(navBar.cataId)">
									<view :class="navIndex == navBar.cataId ? 'listTitle_active' : 'listTitle'"  class="tab-item">
										{{navBar.name}}
									</view>
								</view>
							</block>
						</view>
					</scroll-view>
					<text :class="this.isTrue ? 'inxupt inxupttubiao2' : 'inxupt inxupttubiao23'" class="icon" @tap="toggleIcon()"></text>
				</view>
				<!-- 导航栏 -->
				<view class="navs" :class="{'navOver':navOver}">
					<view class="navBox">
						<view>
							<view class="nav">
								<view v-for="(navBar,index) in navBars" :key="index" class="child"  @tap="swichTab(navBar.cataId)">
									<view :class="navIndex == navBar.cataId ? 'listTitle_active' : 'listTitle'" class="tab-item">{{navBar.name}}</view>
								</view>
							</view>
						</view>
					</view>
				</view>
				
				
			</view>
			</view>
			<!-- 展示帖子摘要 -->
			<view class="summary">
				<swiper
					:style="'height:' + swiperItemHeight + 'px;'"
					@change="swiperChange" 
					:current="activeSwiper">
					<swiper-item v-for='(outerItem,outerIndex) in normalList' :key='outerIndex'>
						<view :class="activeSwiper == outerIndex ? 'page page_active' : 'page'">
							<view v-for='(item,index) in outerItem' :key="index">
								<!-- 学术贴摘要 -->
								<AcademicSummary v-if='item.type === 2' :datas="item"></AcademicSummary> 
								<!-- 普通贴摘要 -->
								<PostingsSummary v-else-if='item.type === 1' :datas="item"></PostingsSummary>
							</view>	
							<UniLoadMore :status="status" color="#7F7F7F" :contentText="contentText"></UniLoadMore>
						</view>
					</swiper-item>
				</swiper>
			</view>
			<!-- 创建学术或普通帖子 -->
			<uni-fab horizontal="right"
				 direction="vertical"
				 :pattern="pattern"	
				 :content="content"
				 @trigger="trigger"
				 v-if='isLogin'
				></uni-fab>					
			</view>
		</view>
</template>
 
<script>
	import ErrorPage from '../../components/ErrorPage.vue'
	import UniLoadMore from '../../components/plugins/uni-load-more.vue'
	import SearchBox from '../../components/SearchBox.vue'
	import Level from '../../components/Level.vue'
	import AcademicSummary from '../../components/summary/AcademicSummary.vue'
	import PostingsSummary from '../../components/summary/PostingsSummary.vue'
	import { _ajax } from '../../in-xupt-functions.js'	
	import UniFab from '../../components/plugins/uni-fab/uni-fab.vue'
	export default {
		components: {
			SearchBox,
			Level,
			AcademicSummary,
			PostingsSummary,
			UniLoadMore,
			ErrorPage,
			UniFab
		},
		data() {
			return {
				err: false,
				activeSwiper: 0,
				loadingHeight: 0, // 遮罩层高度
				isLoading: true, // 是否处于加载状态
				myAvatar: '',	//	我的头像
				isLogin: false,	//是否登陆，默认未登录
				categoryId: 0,	//标签Id
				messages_num: '0',	//消息数量
				mylevel: 1, //等级
				navIndex:0,
				navOver: true,
				current: 0,
				navBars:[
					{name: '全部',cataId: 0},
					{name: '学习',cataId: 1},
					{name: '生活',cataId: 2},
					{name: '失物招领',cataId: 3},
					{name: '分享感悟',cataId: 4},
					{name: '表白',cataId: 5},
					{name: '找人',cataId: 6},
					{name: '寻物启事',cataId: 7},
					{name: '求购',cataId: 8},
					{name: '出售',cataId: 9},
					{name: '拼团',cataId: 10},
					{name: '考研',cataId: 11},
					{name: '活动宣传',cataId: 12},
					{name: '纳新',cataId: 13},
					{name: '找队友',cataId: 14},
					{name: '编程',cataId: 15},
					{name: '二次元',cataId: 16},
					{name: '美食',cataId: 17},
					{name: '美妆',cataId: 18},
					{name: '新闻',cataId: 19},
					{name: '周边',cataId: 20},
					{name: '其他',cataId: 21}
				],
				isTrue: true,
				content: [
							{text: '帖子'},
							{text: '文章'},
						 ], // 悬浮球弹窗								
				pattern: {
					buttonColor: '#F76B8A'
				},// 悬浮球配置
				normalList: [[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[]], //帖子数组
				// 加载帖子列表所需变量
				status: "more",
				contentText: {
					contentdown: "下拉翻找更多东西",   //loading前的文字显示
					contentrefresh: "正在翻找~~",    //loading中的显示
					contentnomore: "没有东西啦！"    //没有更多的显示
				},
				swiperItemHeight: 0, // swiper容器的高度
				pageNum: 1,
				pageSize: 10,
				nowPage: 1,
				pageSizeAll: 10,
				nowPageAll: 1,
				userId: undefined,
				translateLeft: 0,//距左侧距离
				animationData: {},
				scrollLeft: 0,	// 滚动的距离
				swiperLeft: 0,
				subLeft: 0,	//点击元素距离屏幕左边的距离
				subHulfWidth: 0,	//	点击元素的宽度的一半
				screenHalfWith: 0,  //屏幕宽度的一半
				progressNum:0,
				loadingWidth: 0	//设备宽度
			}
		},
		methods: {
			solveTrans(e) {
				console.log(e)
			},
			toMessage() {
				if(this.isLogin) {
					uni.navigateTo({
						animationType:'slide-in-bottom',
						url:'../Messages/Messages'
					})
				}else {
					uni.showModal({
						// 当用户未登录时，token为空时，提示登录
						content: "还没有登录哦~要现在前往登录吗？",
						confirmText: "要要要！",
						cancelText: "下次一定！",
						success:function(btn){
							if (btn.confirm) {
								// token校验失败前往登录时，清空token和userId
								uni.removeStorageSync('userId');
								uni.removeStorageSync('token');
								uni.redirectTo({
									url: '../Login/Login'
								})
							}
							if (btn.cancel) {
								uni.hideLoading()
								return
							}
						}
					})
				}
			},
			// 搜索框跳转
			searchTo() {
				uni.navigateTo({
					// url: '../Search/Search'
					url: '../Search/Search'
				})
			},
			// 我的主页跳转
			myInforTo(){
				uni.navigateTo({
					url: '../Mine/Mine',
					animationType: 'slide-in-left',
					animationDuration: 300
				})
			},
			// 点击上方tab栏的项目时，更新当前index (activeSwiper)
			swichTab: function (index) {
				this.activeSwiper = index
				this.categoryId = this.navBars[this.activeSwiper].cataId
			},
			// 当滑动swiper或者点击导航栏上的选择项目时，重新获取swiper高度
			swiperChange: function (data) {
				uni.pageScrollTo({
					scrollTop: 0
				})
				this.activeSwiper = data.detail.current;
				this.categoryId = this.navBars[this.activeSwiper].cataId
				this.swiperNav(this.categoryId)
			},
			getheight: function(time) {
				setTimeout(() => {
					// 获取当前swiper-item的高度
					let query = uni.createSelectorQuery();
					let page_active = query.select(".page_active");
					page_active.fields({
						size: true
					}, data => {
						// 获取当前设备的高度，取swiper高度为设备高度和swiper-item高度的最大值 （这个方法有bug）
						uni.getSystemInfo({
							success: (data2) => {
								if (data.height <= data2.windowHeight) {
									this.status = 'nomore'
								}
								this.swiperItemHeight = Math.max(data2.windowHeight - 80, data.height) + 20;
							}
						})
						uni.hideLoading()
					}).exec();
				},time)
			},

			// 展开图标的状态
			toggleIcon() {
				this.isTrue = !this.isTrue
				this.navOver = !this.navOver
			},
			// 切换
			isShow(navIndex) {
				if(navIndex == 0) {
					return true
				}else {
					return false
				}
			},
			
			// 悬浮球item点击
			trigger(item) {
				let _self = this 
				if(item.index === 0) {
					// 跳转文章编辑页
					uni.navigateTo({
						url: '../PostingsEdit/PostingsEdit'
					})
				} else {
					// 跳转帖子编辑页
					uni.navigateTo({
						url: '../AcademicEdit/AcademicEdit'
					})
				}	
			},
			// 页面头像
			isLogins: function() {
				_ajax({
					url: '/user/page',
					method: 'GET',
				},true).then(res=>{
					if(res.data.data.avatarUrl) {
						this.myAvatar = res.data.data.avatarUrl
						this.isLogin = true
						this.mylevel = res.data.data.level
					} 				
				})	
			},
			
			
			// 展示全部帖子
			isShowAll() {				
				_ajax({
					url: '/posts?pageNum=1&pageSize=10',
					method: 'GET',
				}).then(res => {
					if(res.data.status == 0) {
						this.normalList[0].push(...res.data.data.list)
						this.isLoading = false;
						this.err = false;
						this.getheight(500);
						uni.stopPullDownRefresh()
					}else {
						uni.showToast({
							icon:'none',
							title: res.data.msg
						})
						this.isLoading = false;
						this.err = true;
					}
				})
				.catch(err => {
					this.isLoading = false;
					this.err = true;
				})
			},
			
			// 滑动标签
			swiperNav(categoryId) {
				this.normalList = [[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[]];
				this.nowPage = 1; // 初始化分页
				this.nowPageAll = 1; // 初始化分页
				this.status = 'more'
				if(categoryId !== 0) {
					_ajax({
						url: '/category/'+ categoryId + '/posts?'+'pageNum=' + 1 + '&pageSize=' + 10,
						method: 'GET',
					}).then(res => { 
						this.normalList[categoryId].push(...res.data.data.list)
						this.getheight(500)
						uni.stopPullDownRefresh()
					})
				}else {
					this.isShowAll()
				}
				this.navIndex = categoryId
				if(this.isTrue == false && this.navOver == false) {
					this.isTrue = !this.isTrue
					this.navOver = !this.navOver
				}
				// 获取当前swiper-item的宽度
				let query = uni.createSelectorQuery();
				let tab_item = query.selectAll(".tab-item");
				tab_item.fields({
					rect:true,
					size: true
				}, data => {
					this.subLeft = data[this.categoryId].left
					this.subHulfWidth = data[this.categoryId].width
					let widths = 0
					for(let i = 0;i < categoryId;i++) {
						widths += data[i].width + 20
					}
					if(widths > this.loadingWidth/2) {
						this.scrollLeft = widths + data[this.categoryId].width/2 - this.loadingWidth/2
					}else {
						this.scrollLeft = 0
					}
				}).exec()
			},
			// 标签页上拉加载
			loadMore() {
				this.status = "loading";
				let _self = this
				if(_self.categoryId === 0) {
					_self.nowPageAll++
					console.log('请求数据')
					_ajax({
						url: '/posts?pageNum='+ _self.nowPageAll+'&pageSize='+_self.pageSizeAll,
						method: 'GET'
					}).then(res => { 
						console.log(res)
						if(res.data.data.isLastPage) {
							console.log('这是最后一页了！')
							_self.status = 'nomore'
						}else {
							_self.status = 'more'
							_self.normalList[0].push(...res.data.data.list)
						}
						_self.getheight(500)
					})
				}else {
					_self.nowPage++
					_ajax({
						url: '/category/'+ this.categoryId + '/posts?pageNum='+ _self.nowPage + '&pageSize='+_self.pageSize,
						method: 'GET'
					}).then(res => {
						if(res.data.data.isLastPage) {
							console.log('这是最后一页了！')
							_self.status = 'nomore'
						}else {
							_self.status = 'more'
							_self.normalList[_self.categoryId].push(...res.data.data.list)
							_self.getheight(500)
						}
					})
				}	

			},
			reloadPage: function() {
				this.err = false;
				this.isLoading = true;
				this.isShowAll();
				this.isLogins()
			},
			resetData: function(flag) {
				// 重置数据
				// 定义flag为true时是在新鲜事页的下拉刷新
				if(!flag) {
					this.activeSwiper = 0;
					this.isLoading = true;
					this.myAvatar = '';
					this.isLogin = false;
					this.categoryId = 0;
					this.navIndex = 0;
					this.navOver = true;
				}
				this.normalList = [[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[]];
				this.status = 'more';
				this.swiperItemHeight = 0;
				this.pageNum = 1;
				this.nowPage = 1;
				this.nowPageAll = 1;
				this.isTrue = true;
			}
	},
		onReachBottom: function() {
			if(this.status == 'nomore' || this.status == 'loading') {
				return
			} else {
				this.loadMore(this.catagoryId)
			}
		},
		onLoad: function(options){
			// 得到屏幕高度，并将这个值设置为加载遮罩层的高度
			uni.getSystemInfo({
				success: (data) => {
					this.loadingHeight = data.windowHeight;
					this.loadingWidth =  data.windowWidth
				}
			})
			this.userId = uni.getStorageSync('userId');
			this.animation = uni.createAnimation();
			this.isShowAll()
			this.isLogins()
		},
		// 点击导航栏回到顶部
		onTabItemTap: function (e) {
			this.isLogins()
		},
		onShow: function () {
			_ajax({
				url: '/notice/num'
			})
			.then(res => {
				if(res.data.status == 0) {
					this.messages_num = res.data.data
				}
			})
			if(uni.isRefresh) {
				// 重置数据
				this.resetData()
				// 请求
				this.isShowAll()
				this.isLogins()
				uni.isRefresh = false;
			}
			
		},
		onPullDownRefresh: function () {
			this.resetData(true);
			this.isLogins();
			this.swiperNav(this.categoryId);
			_ajax({
				url: '/notice/num'
			})
			.then(res => {
				if(res.data.status == 0) {
					this.messages_num = res.data.data
				}
			})
		}
	}
</script>


<style lang="less">
	// 顶部
	@statusHeight: var(--status-bar-height);
	.status_bar {
		height: @statusHeight;
		width: 100%;
		background-color: #FFFFFF;
		position: fixed;
		top: 0rpx;
		z-index: 2;
	}
	.top-nav {
		width: 100%;
		position: fixed;
		top: @statusHeight;
		z-index: 10;
		// 头像、搜索框、消息按钮
		.top {
			display: flex;
			justify-content: space-around;
			width: 100%;
			height: 50px;
			align-items: center;
			position: relative;
			padding: 5px;
			box-sizing: border-box;
			background-color: #ffffff;
			// 头像样式
			.avatar {
				width: 40px;
				height: 40px;
				image {
					width: 40px;
					height: 40px;
					border-radius: 50%;
				}
				// 未登录状态
				.notLogin{
					color: @g-pink;
					width: 40px;
					height: 40px;
					line-height: 40px;
					font-size: 14px;
					text-align: center;
					border-radius: 50%;
					// border: 5rpx solid @uni-border-color;
					background-color: @uni-border-color;
				}
				// 登录后状态
				.login {
					position: relative;
					.mylevel {
						position: absolute;
						z-index: 10;
						bottom: 10%;
						left: 9%;
					}
				}
			}
			// 消息按钮
			.information {
				position: relative;
				.inxupttubiao1{
					display: block;
					text-align: center;
					font-size: 24px;
				}
				.infoCount {
					position: absolute;
					top: -5px;
					right: -5px;
					width: 14px;
					height: 14px;
					border-radius: 50%;
					background-color: @g-pink;
					font-size: 8px;
					text-align: center;
					line-height: 14px;
					color: @uni-text-color-inverse;
					z-index: 10;
				} 
				
			}
			// 新增
			.listTitle,
			.listTitle_active {
				display: inline-block;
				line-height: 30px;
				width: 50%;
				text-align: center;
				// color: @g-pink;
			}
			
		}
		
		// 导航
		.navs {
			position: relative;
			background-color: @uni-bg-color;
			z-index: 10;
			// padding-top: 5px;
			.navBox {
				position: relative;
				height: 0rpx;
				.nav {
					color: @g-gray;
					display: flex;
					align-items: center;
					flex-wrap: wrap;
					background-color: @uni-bg-color;
					box-shadow:0px 10px 10px -10px rgba(0, 0, 0, 0.2);
					.child {
						margin: 10rpx 2%;
					}
					.listTitle_active {
						color: @g-pink;
					}
				}
			}
			.active {
				color: @g-pink;
			}
		}
		.navOver {
			overflow: hidden;
		}	
	}
	.swiperNav {
		position: relative;
		background-color: @uni-bg-color;
		z-index: 10;
		// margin-top: -39px;
		padding-right: 70rpx;
		
		.scroll-tab {
			color: @g-gray;
			white-space: nowrap;
		} 
		.scroll-tab-item {
			display: inline-block;
			margin: 5px 2%;
		}
		.listTitle,
		.listTitle_active {
			display: inline-block;
			line-height: 30px;
			text-align: center;
			font-size: 16px;
		}
		.listTitle_active {
			color: @g-pink;
		}
		.icon {
			position: absolute;
			right: 10rpx;
			bottom: 10px;
			font-size: 16px;
			z-index: 100;
		}
	}
	// 摘要
	.summaryList {
		width: 100%;
	}
	.summary {
		width: 100%;
		position: relative;
		background-color: @g-background;
		padding-top: calc(100px + @statusHeight);
	}
</style>
